<template>
  <div class="UserManagement">
    <div class="UserBox">
      <div class="UserManageHeader">
        <div class="addUser">
          <div class="demo-input-suffix">
            <el-input
                placeholder="搜索姓名"
                @keydown.enter="handleSearch"
                v-model="searchText"
            >
              <template v-slot:prefix>
                <el-icon>
                  <el-icon-search/>
                </el-icon>
              </template>
            </el-input>
          </div>
        </div>
        <el-button type="primary" @click="openEditDialog">添加用户</el-button>
        <el-button @click="exportSelectedUsers">导出</el-button>
      </div>

      <div class="UserTable">
        <el-table :data="tableData" stripe style="width: 100%" ref="userTable" :fit="true">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
              prop="name"
              label="姓名:"
              width="120"
          ></el-table-column>
          <el-table-column prop="campus" label="校区:" width="100">
            <template v-slot="scope">
              {{ getCampusName(scope.row.campus) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="department"
              label="所属部门:"
              width="120"
          >
            <template v-slot="scope">
              {{ getDepartmentName(scope.row.department) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="username"
              label="账号:"
              width="120"
          ></el-table-column>
          <el-table-column
              prop="contact"
              label="手机号:"
              width="120"
          ></el-table-column>
          <el-table-column
              prop="email"
              label="邮箱："
              width="180"
          ></el-table-column>
          <el-table-column prop="userType" label="用户类型:" width="120">
            <template v-slot="scope">
              <span v-if="scope.row.userType === 1">管理员</span>
              <span v-else>普通用户 <el-button
                  text
                  size="small"
                  class="fun-button"
                  @click="openEditUserType(scope.row)">设置为管理员</el-button></span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template v-slot="scope">
              <div>
                <el-button
                    text
                    size="small"
                    class="fun-button"
                    @click="openEditDialog(scope.row)"
                >修改
                </el-button>
              </div>
              <el-button
                  text
                  size="small"
                  class="fun-button"
                  @click="resetUser(scope.row)"
                  style="color: red"
              >重置密码
              </el-button>
              <el-button
                  text
                  size="small"
                  class="fun-button"
                  @click="confirmDelete(scope.row)"
                  style="color: red"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="Pagination">
        <el-pagination
            background
            :page-sizes="[5, 10]"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :current-page="pagination.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <user-form-dialog
        ref="userFormDialog"
        :user="currentUser"
        @save="saveUser"
        :department-tree="departmentTree"
    ></user-form-dialog>
  </div>
</template>

<script>
import {Search as ElIconSearch} from '@element-plus/icons'
import {
  FetchUsers,
  RegisterUser,
  UpdateUserInfo,
  RemoveUser,
  ResetUserPassword,
  UpadateAdmin, GetDepartmentTree, GetDepartmentList,
} from '@/api/index'
import UserFormDialog from '@/components/UserFormDialog.vue'
import _ from 'lodash' // 引入 lodash 库
export default {
  components: {
    UserFormDialog,
    ElIconSearch,
  },
  name: 'UserManagement',
  data() {
    return {
      searchText: '',
      pagination: {
        pageNum: 1,
        pageSize: 5,
        total: 0,
      },
      tableData: [],
      currentUser: null,
      departmentTree: [],
      departmentList: [],

    }
  },
  methods: {
    getDepartmentName(departmentId) {
      if (departmentId) {
        const department = this.departmentList.find(item => item.id === departmentId);
        return department ? department.name : '未知部门';
      }
      return "无"
    },
    loadDepartments() {
      GetDepartmentList().then(res => {
        if (res.code === 200) {
          this.departmentList = res.data;
        }
      })
      GetDepartmentTree().then((res) => {
        if (res.code === 200) {
          this.departmentTree = res.data;
        }
      });
    },
    getCampusName(campusId) {
      const campus = this.campusList.find((item) => item.id === campusId)
      return campus ? campus.campusName : '未知校区'
    },
    exportSelectedUsers() {
      const selected = this.$refs.userTable.selection
      if (selected.length === 0) {
        this.$message.warning('请至少选择一条记录')
        return
      }

      // 添加UTF-8的BOM
      let csvContent = '\uFEFF'
      csvContent += '姓名,单位,账号,手机号,邮箱\n' // 添加表头
      selected.forEach((user) => {
        const row = `${user.name},${user.department},${user.username},${user.contact},${user.email}`
        csvContent += row + '\n'
      })

      const encodedUri = encodeURI(`data:text/csv;charset=utf-8,${csvContent}`)
      const link = document.createElement('a')
      link.setAttribute('href', encodedUri)

      link.setAttribute('download', 'user_data.csv')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    openEditDialog(user = {}) {
      // 默认参数为空对象，用于添加新用户
      this.currentUser = user
      this.$refs.userFormDialog.openDialog()
    },
    // 设置用户为管理员
    openEditUserType(row) {
      const userData = row
      //设置用户标识为管理员
      userData.userType = 1
      // 调用 API 设置用户为管理员
      UpadateAdmin(userData).then((response) => {
        if (response.code === 200) {
          this.loadUsers()
          this.$message.success(`设置用户${userData.name}为管理员成功"`)
        } else {
          this.$message.error(
              response.msg || `设置用户${userData.name}为管理员失败`
          )
        }
      })
    },
    saveUser(userData) {
      if (userData.id) {
        // 调用更新用户的API
        this.updateUser(userData)
      } else {
        // 调用新增用户的API
        this.addUser(userData)
      }
    },
    addUser(userData) {
      userData.password = 'wfit123456'
      // 调用 API 添加用户
      RegisterUser(userData).then((response) => {
        if (response.code === 200) {
          this.loadUsers()
        } else {
          this.$message.error(response.msg || '添加用户失败')
        }
      })
    },
    updateUser(userData) {
      // 调用 API 更新用户
      UpdateUserInfo(userData).then((response) => {
        if (response.code === 200) {
          this.loadUsers()
          this.$message.success('用户信息更新成功')
        } else {
          this.$message.error(response.msg || '更新用户信息失败')
        }
      })
    },
    resetUser(user) {
      ResetUserPassword({id: user.id}).then((response) => {
        if (response.code === 200) {
          this.$message.success('用户密码重置成功')
          this.loadUsers()
        } else {
          this.$message.error('用户密码重置失败')
        }
      })
    },
    confirmDelete(user) {
      // 可以使用 Element UI 的 MessageBox 确认操作
      this.$confirm('确认删除该用户?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            RemoveUser([user.id]).then((response) => {
              if (response.code === 200) {
                this.$message.success('用户删除成功')
                this.loadUsers()
              } else {
                this.$message.error('删除用户失败')
              }
            })
          })
          .catch(() => {
            this.$message.info('取消删除')
          })
    },
    loadUsers() {
      const params = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        name: this.searchText.trim(),
      }
      FetchUsers(params)
          .then((response) => {
            if (response.code === 200) {
              this.tableData = response.data.rows
              this.pagination.total = Number(response.data.total)
            } else {
              this.$message.error('Failed to fetch users: ' + response.msg)
            }
          })
          .catch((error) => {
            this.$message.error('Error fetching users: ' + error)
            console.error('Error fetching users:', error)
          })
    },
    handleCurrentChange(newPage) {
      this.pagination.pageNum = newPage
      this.loadUsers() // 当页码改变时重新加载数据
    },
    handleSizeChange(newSize) {
      this.pagination.pageSize = newSize
      this.loadUsers()
    },
    handleSearch() {
      this.pagination.pageNum = 1 // 重置到第一页
      this.loadUsers()
    },
  },
  created() {
    this.loadUsers()
    this.loadDepartments(); // 加载部门数据
  },
  computed: {
    campusList() {
      return this.$store.getters.getCampusList
    },
  }
}
</script>

<style lang="less" scoped>
@import '@/assets/style/UserManagement.less';
</style>
